# 创建优惠券管理页面
<template>
  <div class="coupon-management">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="statistics-cards">
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>优惠券总数</span>
            </div>
          </template>
          <div class="card-content">
            <div class="amount">{{ statistics.totalCoupons }}</div>
            <div class="trend">
              较上月
              <span :class="statistics.couponTrend >= 0 ? 'up' : 'down'">
                {{ Math.abs(statistics.couponTrend) }}%
                <el-icon>
                  <component :is="statistics.couponTrend >= 0 ? 'ArrowUp' : 'ArrowDown'" />
                </el-icon>
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>已发放数量</span>
            </div>
          </template>
          <div class="card-content">
            <div class="amount">{{ statistics.issuedCoupons }}</div>
            <div class="percentage">
              占比 {{ statistics.issuedPercentage }}%
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>已使用数量</span>
            </div>
          </template>
          <div class="card-content">
            <div class="amount">{{ statistics.usedCoupons }}</div>
            <div class="percentage">
              使用率 {{ statistics.usedPercentage }}%
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>本月发放</span>
            </div>
          </template>
          <div class="card-content">
            <div class="amount">{{ statistics.monthlyIssued }}</div>
            <div class="trend">
              较上月
              <span :class="statistics.monthlyTrend >= 0 ? 'up' : 'down'">
                {{ Math.abs(statistics.monthlyTrend) }}%
                <el-icon>
                  <component :is="statistics.monthlyTrend >= 0 ? 'ArrowUp' : 'ArrowDown'" />
                </el-icon>
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 优惠券列表 -->
    <el-card class="coupon-card">
      <template #header>
        <div class="card-header">
          <div class="search-form">
            <el-form :model="searchForm" inline>
              <el-form-item label="优惠券类型">
                <el-select v-model="searchForm.type" placeholder="请选择" clearable>
                  <el-option label="全部" value="" />
                  <el-option label="满减券" value="discount" />
                  <el-option label="折扣券" value="percentage" />
                  <el-option label="无门槛券" value="fixed" />
                </el-select>
              </el-form-item>
              <el-form-item label="使用状态">
                <el-select v-model="searchForm.status" placeholder="请选择" clearable>
                  <el-option label="全部" value="" />
                  <el-option label="未开始" value="not_started" />
                  <el-option label="进行中" value="active" />
                  <el-option label="已结束" value="ended" />
                  <el-option label="已停用" value="disabled" />
                </el-select>
              </el-form-item>
              <el-form-item label="关键词">
                <el-input
                  v-model="searchForm.keyword"
                  placeholder="优惠券名称/编码"
                  clearable
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleSearch">查询</el-button>
                <el-button @click="handleReset">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
          <div class="action-buttons">
            <el-button type="primary" @click="handleAddCoupon">创建优惠券</el-button>
            <el-button type="success" @click="handleBatchIssue">批量发放</el-button>
            <el-button type="warning" @click="handleExport">导出数据</el-button>
            <el-button 
              type="danger" 
              :disabled="!selectedCoupons.length"
              @click="handleBatchDelete"
            >
              批量删除
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="couponList"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="优惠券信息" min-width="300">
          <template #default="{ row }">
            <div class="coupon-info">
              <div class="coupon-name">{{ row.name }}</div>
              <div class="coupon-code">编码：{{ row.code }}</div>
              <div class="coupon-type">{{ getCouponTypeText(row.type) }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="优惠内容" width="200">
          <template #default="{ row }">
            <div class="coupon-value">
              {{ getCouponValueText(row) }}
            </div>
            <div class="coupon-condition" v-if="row.minAmount">
              满{{ row.minAmount }}元可用
            </div>
          </template>
        </el-table-column>
        <el-table-column label="有效期" width="300">
          <template #default="{ row }">
            <div>{{ row.startTime }} 至 {{ row.endTime }}</div>
            <div class="coupon-status">
              <el-tag :type="getStatusType(row.status)">
                {{ getStatusText(row.status) }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="发放情况" width="200">
          <template #default="{ row }">
            <div>已发放：{{ row.issuedCount }}</div>
            <div>已使用：{{ row.usedCount }}</div>
            <div>剩余：{{ row.remainingCount }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEditCoupon(row)">
              编辑
            </el-button>
            <el-button 
              type="success" 
              link 
              @click="handleIssueCoupon(row)"
            >
              发放
            </el-button>
            <el-button 
              :type="row.status === 'disabled' ? 'success' : 'warning'"
              link 
              @click="handleToggleStatus(row)"
            >
              {{ row.status === 'disabled' ? '启用' : '停用' }}
            </el-button>
            <el-button 
              type="danger" 
              link 
              @click="handleDeleteCoupon(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="page.current"
          v-model:page-size="page.size"
          :total="page.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 优惠券表单对话框 -->
    <el-dialog
      v-model="couponDialogVisible"
      :title="couponForm.id ? '编辑优惠券' : '创建优惠券'"
      width="600px"
    >
      <el-form
        ref="couponFormRef"
        :model="couponForm"
        :rules="couponFormRules"
        label-width="100px"
      >
        <el-form-item label="优惠券名称" prop="name">
          <el-input v-model="couponForm.name" placeholder="请输入优惠券名称" />
        </el-form-item>
        <el-form-item label="优惠券类型" prop="type">
          <el-radio-group v-model="couponForm.type">
            <el-radio label="discount">满减券</el-radio>
            <el-radio label="percentage">折扣券</el-radio>
            <el-radio label="fixed">无门槛券</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="优惠内容" prop="value">
          <el-input-number
            v-if="couponForm.type === 'discount' || couponForm.type === 'fixed'"
            v-model="couponForm.value"
            :min="0"
            :precision="2"
            :step="1"
            style="width: 200px"
          >
            <template #prefix>¥</template>
          </el-input-number>
          <el-input-number
            v-else
            v-model="couponForm.value"
            :min="0"
            :max="100"
            :precision="0"
            :step="1"
            style="width: 200px"
          >
            <template #suffix>%</template>
          </el-input-number>
        </el-form-item>
        <el-form-item 
          label="使用门槛" 
          prop="minAmount"
          v-if="couponForm.type !== 'fixed'"
        >
          <el-input-number
            v-model="couponForm.minAmount"
            :min="0"
            :precision="2"
            :step="10"
            style="width: 200px"
          >
            <template #prefix>¥</template>
          </el-input-number>
        </el-form-item>
        <el-form-item label="有效期" prop="validityType">
          <el-radio-group v-model="couponForm.validityType">
            <el-radio label="fixed">固定时间</el-radio>
            <el-radio label="dynamic">领取后生效</el-radio>
          </el-radio-group>
        </el-form-item>
        <template v-if="couponForm.validityType === 'fixed'">
          <el-form-item label="开始时间" prop="startTime">
            <el-date-picker
              v-model="couponForm.startTime"
              type="datetime"
              placeholder="选择开始时间"
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="结束时间" prop="endTime">
            <el-date-picker
              v-model="couponForm.endTime"
              type="datetime"
              placeholder="选择结束时间"
              style="width: 200px"
            />
          </el-form-item>
        </template>
        <template v-else>
          <el-form-item label="生效天数" prop="validDays">
            <el-input-number
              v-model="couponForm.validDays"
              :min="1"
              :max="365"
              :precision="0"
              style="width: 200px"
            />
          </el-form-item>
        </template>
        <el-form-item label="发放数量" prop="totalCount">
          <el-input-number
            v-model="couponForm.totalCount"
            :min="1"
            :precision="0"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="每人限领" prop="perLimit">
          <el-input-number
            v-model="couponForm.perLimit"
            :min="1"
            :precision="0"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="使用说明" prop="description">
          <el-input
            v-model="couponForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入使用说明"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="couponDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleCouponSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 发放优惠券对话框 -->
    <el-dialog
      v-model="issueDialogVisible"
      title="发放优惠券"
      width="500px"
    >
      <el-form
        ref="issueFormRef"
        :model="issueForm"
        :rules="issueFormRules"
        label-width="100px"
      >
        <el-form-item label="发放方式" prop="type">
          <el-radio-group v-model="issueForm.type">
            <el-radio label="all">全部会员</el-radio>
            <el-radio label="level">指定会员等级</el-radio>
            <el-radio label="tag">指定会员标签</el-radio>
            <el-radio label="custom">指定会员</el-radio>
          </el-radio-group>
        </el-form-item>
        <template v-if="issueForm.type === 'level'">
          <el-form-item label="会员等级" prop="levelIds">
            <el-select
              v-model="issueForm.levelIds"
              multiple
              placeholder="请选择会员等级"
            >
              <el-option
                v-for="level in memberLevels"
                :key="level.id"
                :label="level.name"
                :value="level.id"
              />
            </el-select>
          </el-form-item>
        </template>
        <template v-if="issueForm.type === 'tag'">
          <el-form-item label="会员标签" prop="tagIds">
            <el-select
              v-model="issueForm.tagIds"
              multiple
              placeholder="请选择会员标签"
            >
              <el-option
                v-for="tag in memberTags"
                :key="tag.id"
                :label="tag.name"
                :value="tag.id"
              />
            </el-select>
          </el-form-item>
        </template>
        <template v-if="issueForm.type === 'custom'">
          <el-form-item label="会员列表" prop="memberIds">
            <el-select
              v-model="issueForm.memberIds"
              multiple
              filterable
              remote
              :remote-method="handleMemberSearch"
              placeholder="请输入会员手机号搜索"
            >
              <el-option
                v-for="member in memberList"
                :key="member.id"
                :label="member.name + ' (' + member.phone + ')'"
                :value="member.id"
              />
            </el-select>
          </el-form-item>
        </template>
        <el-form-item label="发放数量" prop="count">
          <el-input-number
            v-model="issueForm.count"
            :min="1"
            :max="currentCoupon?.remainingCount || 1"
            :precision="0"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="发放说明" prop="remark">
          <el-input
            v-model="issueForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入发放说明"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="issueDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleIssueSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowUp, ArrowDown } from '@element-plus/icons-vue'
import {
  getMerchantCouponList,
  getMerchantCouponStatistics,
  createMerchantCoupon,
  updateMerchantCoupon,
  deleteMerchantCoupon,
  batchDeleteMerchantCoupons,
  updateMerchantCouponStatus,
  issueMerchantCoupon,
  batchIssueMerchantCoupons,
  exportMerchantCoupons,
  getMerchantMemberLevels,
  getMerchantMemberTags,
  searchMerchantMembers
} from '@/api/merchant'

// 统计数据
const statistics = reactive({
  totalCoupons: 0,
  couponTrend: 0,
  issuedCoupons: 0,
  issuedPercentage: 0,
  usedCoupons: 0,
  usedPercentage: 0,
  monthlyIssued: 0,
  monthlyTrend: 0
})

// 优惠券列表
const loading = ref(false)
const couponList = ref([])
const selectedCoupons = ref([])

// 搜索表单
const searchForm = reactive({
  type: '',
  status: '',
  keyword: ''
})

// 分页
const page = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 优惠券表单
const couponDialogVisible = ref(false)
const couponFormRef = ref(null)
const couponForm = reactive({
  id: '',
  name: '',
  type: 'discount',
  value: 0,
  minAmount: 0,
  validityType: 'fixed',
  startTime: '',
  endTime: '',
  validDays: 30,
  totalCount: 1000,
  perLimit: 1,
  description: ''
})

// 发放表单
const issueDialogVisible = ref(false)
const issueFormRef = ref(null)
const issueForm = reactive({
  type: 'all',
  levelIds: [],
  tagIds: [],
  memberIds: [],
  count: 1,
  remark: ''
})
const currentCoupon = ref(null)

// 会员相关数据
const memberLevels = ref([])
const memberTags = ref([])
const memberList = ref([])

// 表单验证规则
const couponFormRules = {
  name: [{ required: true, message: '请输入优惠券名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择优惠券类型', trigger: 'change' }],
  value: [{ required: true, message: '请输入优惠内容', trigger: 'blur' }],
  minAmount: [{ required: true, message: '请输入使用门槛', trigger: 'blur' }],
  validityType: [{ required: true, message: '请选择有效期类型', trigger: 'change' }],
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
  validDays: [{ required: true, message: '请输入生效天数', trigger: 'blur' }],
  totalCount: [{ required: true, message: '请输入发放数量', trigger: 'blur' }],
  perLimit: [{ required: true, message: '请输入每人限领数量', trigger: 'blur' }]
}

const issueFormRules = {
  type: [{ required: true, message: '请选择发放方式', trigger: 'change' }],
  levelIds: [{ required: true, message: '请选择会员等级', trigger: 'change' }],
  tagIds: [{ required: true, message: '请选择会员标签', trigger: 'change' }],
  memberIds: [{ required: true, message: '请选择会员', trigger: 'change' }],
  count: [{ required: true, message: '请输入发放数量', trigger: 'blur' }]
}

// 获取统计数据
const getStatistics = async () => {
  try {
    const { data } = await getMerchantCouponStatistics()
    Object.assign(statistics, data)
  } catch (error) {
    console.error('获取统计数据失败:', error)
    ElMessage.error('获取统计数据失败')
  }
}

// 获取优惠券列表
const getCouponList = async () => {
  loading.value = true
  try {
    const params = {
      ...searchForm,
      page: page.current,
      size: page.size
    }
    const { data } = await getMerchantCouponList(params)
    couponList.value = data.list
    page.total = data.total
  } catch (error) {
    console.error('获取优惠券列表失败:', error)
    ElMessage.error('获取优惠券列表失败')
  } finally {
    loading.value = false
  }
}

// 获取会员等级列表
const getMemberLevels = async () => {
  try {
    const { data } = await getMerchantMemberLevels()
    memberLevels.value = data
  } catch (error) {
    console.error('获取会员等级列表失败:', error)
  }
}

// 获取会员标签列表
const getMemberTags = async () => {
  try {
    const { data } = await getMerchantMemberTags()
    memberTags.value = data
  } catch (error) {
    console.error('获取会员标签列表失败:', error)
  }
}

// 搜索会员
const handleMemberSearch = async (query) => {
  if (query) {
    try {
      const { data } = await searchMerchantMembers({ keyword: query })
      memberList.value = data
    } catch (error) {
      console.error('搜索会员失败:', error)
    }
  } else {
    memberList.value = []
  }
}

// 搜索
const handleSearch = () => {
  page.current = 1
  getCouponList()
}

// 重置搜索
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  handleSearch()
}

// 选择行变化
const handleSelectionChange = (rows) => {
  selectedCoupons.value = rows
}

// 添加优惠券
const handleAddCoupon = () => {
  Object.keys(couponForm).forEach(key => {
    couponForm[key] = key === 'type' ? 'discount' : 
                      key === 'validityType' ? 'fixed' :
                      key === 'totalCount' || key === 'perLimit' ? 1 :
                      key === 'validDays' ? 30 : 0
  })
  couponForm.id = ''
  couponDialogVisible.value = true
}

// 编辑优惠券
const handleEditCoupon = (row) => {
  Object.assign(couponForm, row)
  couponDialogVisible.value = true
}

// 删除优惠券
const handleDeleteCoupon = async (row) => {
  try {
    await ElMessageBox.confirm('确认删除该优惠券吗？', '提示', {
      type: 'warning'
    })
    await deleteMerchantCoupon(row.id)
    ElMessage.success('删除成功')
    getCouponList()
    getStatistics()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除优惠券失败:', error)
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedCoupons.value.length === 0) {
    ElMessage.warning('请选择要删除的优惠券')
    return
  }
  try {
    await ElMessageBox.confirm('确认删除选中的优惠券吗？', '提示', {
      type: 'warning'
    })
    const ids = selectedCoupons.value.map(row => row.id)
    await batchDeleteMerchantCoupons(ids)
    ElMessage.success('批量删除成功')
    getCouponList()
    getStatistics()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
    }
  }
}

// 提交优惠券表单
const handleCouponSubmit = async () => {
  if (!couponFormRef.value) return
  
  try {
    await couponFormRef.value.validate()
    if (couponForm.id) {
      await updateMerchantCoupon(couponForm.id, couponForm)
      ElMessage.success('更新成功')
    } else {
      await createMerchantCoupon(couponForm)
      ElMessage.success('创建成功')
    }
    couponDialogVisible.value = false
    getCouponList()
    getStatistics()
  } catch (error) {
    console.error('提交优惠券失败:', error)
  }
}

// 发放优惠券
const handleIssueCoupon = (row) => {
  currentCoupon.value = row
  Object.keys(issueForm).forEach(key => {
    issueForm[key] = key === 'type' ? 'all' : key === 'count' ? 1 : []
  })
  issueDialogVisible.value = true
}

// 批量发放
const handleBatchIssue = () => {
  if (selectedCoupons.value.length === 0) {
    ElMessage.warning('请选择要发放的优惠券')
    return
  }
  handleIssueCoupon(selectedCoupons.value[0])
}

// 提交发放表单
const handleIssueSubmit = async () => {
  if (!issueFormRef.value) return
  
  try {
    await issueFormRef.value.validate()
    const params = {
      couponId: currentCoupon.value.id,
      ...issueForm
    }
    if (selectedCoupons.value.length > 1) {
      await batchIssueMerchantCoupons(params)
      ElMessage.success('批量发放成功')
    } else {
      await issueMerchantCoupon(params)
      ElMessage.success('发放成功')
    }
    issueDialogVisible.value = false
    getCouponList()
    getStatistics()
  } catch (error) {
    console.error('发放优惠券失败:', error)
  }
}

// 切换优惠券状态
const handleToggleStatus = async (row) => {
  try {
    const newStatus = row.status === 'disabled' ? 'active' : 'disabled'
    await updateMerchantCouponStatus(row.id, { status: newStatus })
    ElMessage.success('状态更新成功')
    getCouponList()
  } catch (error) {
    console.error('更新状态失败:', error)
  }
}

// 导出优惠券
const handleExport = async () => {
  try {
    const params = {
      ...searchForm
    }
    await exportMerchantCoupons(params)
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 获取优惠券类型文本
const getCouponTypeText = (type) => {
  const map = {
    discount: '满减券',
    percentage: '折扣券',
    fixed: '无门槛券'
  }
  return map[type]
}

// 获取优惠内容文本
const getCouponValueText = (row) => {
  if (row.type === 'discount' || row.type === 'fixed') {
    return `¥${row.value}`
  } else {
    return `${row.value}%`
  }
}

// 获取状态类型
const getStatusType = (status) => {
  const map = {
    not_started: 'info',
    active: 'success',
    ended: 'warning',
    disabled: 'danger'
  }
  return map[status]
}

// 获取状态文本
const getStatusText = (status) => {
  const map = {
    not_started: '未开始',
    active: '进行中',
    ended: '已结束',
    disabled: '已停用'
  }
  return map[status]
}

// 分页大小变化
const handleSizeChange = (val) => {
  page.size = val
  getCouponList()
}

// 页码变化
const handleCurrentChange = (val) => {
  page.current = val
  getCouponList()
}

onMounted(() => {
  getStatistics()
  getCouponList()
  getMemberLevels()
  getMemberTags()
})
</script>

<style lang="scss" scoped>
.coupon-management {
  padding: 20px;

  .statistics-cards {
    margin-bottom: 20px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .card-content {
      text-align: center;

      .amount {
        font-size: 24px;
        font-weight: bold;
        color: #303133;
        margin-bottom: 10px;
      }

      .trend {
        font-size: 14px;
        color: #909399;

        .up {
          color: #67c23a;
        }

        .down {
          color: #f56c6c;
        }
      }

      .percentage {
        font-size: 14px;
        color: #909399;
      }
    }
  }

  .coupon-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .search-form {
        flex: 1;
        margin-right: 20px;
      }

      .action-buttons {
        display: flex;
        gap: 10px;
      }
    }
  }

  .coupon-info {
    .coupon-name {
      font-weight: bold;
      margin-bottom: 5px;
    }

    .coupon-code,
    .coupon-type {
      font-size: 12px;
      color: #909399;
    }
  }

  .coupon-value {
    font-size: 16px;
    font-weight: bold;
    color: #f56c6c;
    margin-bottom: 5px;
  }

  .coupon-condition {
    font-size: 12px;
    color: #909399;
  }

  .coupon-status {
    margin-top: 5px;
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 